<template>
  <div id="mine-order-pending">
    <div class="public-footer-btn-box">
      <button
        class="single-button"
        :disabled="submitDisabled"
        @click="submit">确定</button>
    </div>
    <fill-owner-info
      ref="comp-owner-info"
      type="part"
      :info="ownerInfo"
      :gotLicence="gotLicenceOrNot"
      :editable="true"
      @isOwnerPersonType="isOwnerPersonType"
      v-if="infoReady"></fill-owner-info>

    <div class="public-btn-box pt-1">
      <button class="submit" @click="ocrParseIDToText">OCR识别</button>
    </div>

    <fill-car-info
      ref="comp-car-info"
      type="part"
      :info="carInfo"
      :editable="true"
      :gotLicence="gotLicenceOrNot"
      :gotEvidence="gotEvidenceOrNot"
      v-if="infoReady"></fill-car-info>

    <div class="public-btn-box pt-1" v-if="gotLicenceOrNot">
      <button class="submit" @click="ocrParseLicenceToText">OCR识别</button>
    </div>

    <fill-insurance-policy
      ref="comp-policy-info"
      type="part"
      :info="policyInfo"
      :editable="true"
      v-if="infoReady && policy_id"></fill-insurance-policy>
  </div>
</template>

<script>
  import FillOwnerInfo from '../comp/comp-fill-owner-info.vue';
  import FillCarInfo from '../comp/comp-fill-car-info.vue';
  import FillInsurancePolicy from '../comp/comp-fill-insurance-policy.vue';
  export default {
    name: "mine-order-pending",
    components: {
      FillOwnerInfo,
      FillCarInfo,
      FillInsurancePolicy
    },
    data() {
      return {
        ownerInfo: {},
        carInfo: {},
        policyInfo: {},
        infoReady: false,
        gotLicenceOrNot: false,
        gotEvidenceOrNot: false,
        submitDisabled: false,
        car_owner_id: '',
        car_id: '',
        policy_id: '',
        type: ''
      }
    },
    methods: {
      // 更改信息
      submit() {

        let allValidated = true;

        let ownerInfoRef = this.$refs['comp-owner-info'];
        let carInfoRef = this.$refs['comp-car-info'];
        let policyInfoRef = this.$refs['comp-policy-info'];

        // 有订单id

        if (this.policy_id) {
          Promise.all([
            ownerInfoRef.$validator.validateAll(),
            carInfoRef.$validator.validateAll(),
            policyInfoRef.$validator.validateAll()
          ]).then(values => {
            values.forEach(value => {
              if (!value) {
                allValidated = false;
              }
            });

            // 请求
            if (policyInfoRef.formTwo.effectTiming === '2' && policyInfoRef.customInsuranceEffectDate === '请选择-请选择-请选择') {
              alert('请选择保单生效日期。');
            } else if (allValidated) {
              this.$http.post({
                api: this.$api.INSURANCE_INFO_CONFIRM,
                params: {
                  car_owner_id: {
                    car_owner_type: ownerInfoRef.ownerType,

                    name: ownerInfoRef.ownerName,
                    num: ownerInfoRef.ownerIdNum,
                    end_date: ownerInfoRef.idEndDate,
                    phone: ownerInfoRef.ownerTel,
                    address: ownerInfoRef.ownerAddress,
                    linkman: ownerInfoRef.contact,
                    sex: ownerInfoRef.contactGender,
                    id_card_face: ownerInfoRef.idFrontImg,
                    id_card_back: ownerInfoRef.idBackImg,
                    user_id: localStorage.getItem('id'),

                    // 新增时 必传 (有行驶证)

                    plate_num: ownerInfoRef.licence,
                    plate_num_type: ownerInfoRef.licenceTypeCode,

                    // 修改时 必传 (有行驶证)

                    car_owner_id: this.car_owner_id
                  },
                  car_id: {
                    car_owner_id: this.car_owner_id,

                    /**
                     * 表单一
                     */
                    model: (carInfoRef.formOne.carBrand).replace('牌', ''),
                    provice: carInfoRef.formOne.aboutPlace.placeCode,
                    traffic: carInfoRef.formOne.aboutType.typeCode,
                    vin: (carInfoRef.formOne.carNum).toUpperCase(),
                    engine_num: (carInfoRef.formOne.carEngineNum).toUpperCase(),
                    buy_time: carInfoRef.carEffectDate,
                    car_nature: carInfoRef.formOne.usage,
                    is_local: carInfoRef.formOne.locale,
                    nature: carInfoRef.formOne.belong,
                    transfer: carInfoRef.formOne.newly,
                    transfer_date: carInfoRef.carTransferDate,
                    mortgage: carInfoRef.formOne.mortgage,
                    beneficiary: carInfoRef.formOne.beneficiary,
                    scale: carInfoRef.formOne.benefitProportion,
                    special_agreement: carInfoRef.formOne.specially,

                    taxes_type: carInfoRef.formOne.aboutTaxesType.taxesTypeCode,
                    taxes_reason: carInfoRef.formOne.aboutTaxesReductionReason.taxesReductionReasonCode,
                    taxes_code: carInfoRef.formOne.taxesReductionReasonCodeLong,
                    taxes_organ: carInfoRef.formOne.taxesDepartment,
                    taxes_program: carInfoRef.formOne.aboutTaxesReductionPlan.taxesReductionPlanCode,
                    taxes_no: carInfoRef.formOne.taxesNo,
                    taxes_amount: carInfoRef.formOne.taxesReduction,
                    taxes_proportion: carInfoRef.formOne.taxesReductionRate / 100 || 0,
                    fuel_type: carInfoRef.formOne.aboutEnergy.energyCode,

                    /**
                     * 表单二
                     */
                    insured: carInfoRef.formTwo.recognizeeSameAsOwner,

                    // 被保人信息（非必传）

                    insured_name: carInfoRef.formTwo.recognizeeSameAsOwner === '1' ? '' : carInfoRef.formTwo.recognizee,
                    insured_num: carInfoRef.formTwo.recognizeeSameAsOwner === '1' ? '' : carInfoRef.formTwo.recognizeeIdNum,
                    insured_phone: carInfoRef.formTwo.recognizeeSameAsOwner === '1' ? '' : carInfoRef.formTwo.recognizeeTel,

                    policy_holder: carInfoRef.formTwo.applicant,

                    // 投保人信息（非必传）

                    policy_name: carInfoRef.formTwo.applicantName,
                    policy_num: carInfoRef.formTwo.applicantIdNum,
                    policy_phone: carInfoRef.formTwo.applicantTel,

                    /**
                     * 表单三
                     */

                    car_url: carInfoRef.carPicturesArr,
                    remark: carInfoRef.otherPicturesArr,
                    certificate_url: carInfoRef.formThree.evidence[0].img,
                    invoice: carInfoRef.formThree.evidence[1].img,

                    // 有车牌时必传（修改）

                    car_id: this.car_id,
                    driving_face: carInfoRef.formThree.licence[0].img,
                    driving_back: carInfoRef.formThree.licence[1].img,
                    invoice2: carInfoRef.formThree.licence[2].img
                  },
                  policy_id: {
                    car_owner_id: this.car_owner_id,
                    car_id: this.car_id,
                    user_id: localStorage.getItem('id'),

                    /**
                     * 表单一
                     */
                    is_get: policyInfoRef.formOne.needEvidence,
                    mail: policyInfoRef.formOne.byMail,
                    name: policyInfoRef.formOne.receiverName,
                    phone: policyInfoRef.formOne.receiverTel,
                    address: policyInfoRef.receiverAddress,

                    /**
                     * 表单二
                     */
                    is_immefc: policyInfoRef.formTwo.effectTiming,
                    start_time: policyInfoRef.formTwo.effectTiming === '1' ?
                      policyInfoRef.insuranceEffectDate + ' ' + (23 - policyInfoRef.formTwo.advancedInsuranceEffectTime) + ':00:00' :
                      policyInfoRef.customInsuranceEffectDate + ' 00:00:00',
                    hours: policyInfoRef.formTwo.advancedInsuranceEffectTime,

                    jq_is_immefc: policyInfoRef.formTwo.jqEffectTiming,
                    jq_start_time: policyInfoRef.formTwo.jqEffectTiming === '1' ?
                      policyInfoRef.jqInsuranceEffectDate + ' ' + (23 - policyInfoRef.formTwo.jqAdvancedInsuranceEffectTime) + ':00:00' :
                      policyInfoRef.jqCustomInsuranceEffectDate + ' 00:00:00',
                    jq_hours: policyInfoRef.formTwo.jqAdvancedInsuranceEffectTime,

                    // 修改时必传
                    policy_id: this.policy_id
                  }
                },
                success: (res) => {

                  this.$tool.whenToast(
                    () => {

                      // 不再恢复，组件即将销毁

                      this.submitDisabled = false;
                    },
                    {
                      message: '提交成功，请继续选择险种',
                      className: 'public-long-toast',
                      duration: -1
                    },
                    () => {
                      this.$router.push({
                        name: 'FillInsuranceDetail',
                        params: {
                          type: this.type,
                          car_owner_id: this.car_owner_id,
                          car_id: this.car_id,
                          policy_id: this.policy_id
                        }
                      });
                    },2000
                  );
                }
              });
            }
          });

          // 无订单id

        } else if (!this.policy_id) {
          Promise.all([ownerInfoRef.$validator.validateAll(), carInfoRef.$validator.validateAll()]).then(values => {
            values.forEach(value => {
              if (!value) {
                allValidated = false;
              }
            });

            // 请求
            if (allValidated) {
              this.$http.post({
                api: this.$api.INSURANCE_OWNER_CAR_INFO,
                params: {
                  car_owner_id: {
                    car_owner_type: ownerInfoRef.ownerType,

                    name: ownerInfoRef.ownerName,
                    num: ownerInfoRef.ownerIdNum,
                    end_date: ownerInfoRef.idEndDate,
                    phone: ownerInfoRef.ownerTel,
                    address: ownerInfoRef.ownerAddress,
                    linkman: ownerInfoRef.contact,
                    sex: ownerInfoRef.contactGender,
                    id_card_face: ownerInfoRef.idFrontImg,
                    id_card_back: ownerInfoRef.idBackImg,
                    user_id: localStorage.getItem('id'),

                    // add、continue 时 必传 (有行驶证)

                    plate_num: ownerInfoRef.licence,
                    plate_num_type: ownerInfoRef.licenceTypeCode,

                    // 修改时 必传 (有行驶证)

                    car_owner_id: this.car_owner_id
                  },
                  car_id: {
                    car_owner_id: this.car_owner_id,

                    /**
                     * 表单一
                     */
                    model: (carInfoRef.formOne.carBrand).replace('牌', ''),
                    provice: carInfoRef.formOne.aboutPlace.placeCode,
                    traffic: carInfoRef.formOne.aboutType.typeCode,
                    vin: (carInfoRef.formOne.carNum).toUpperCase(),
                    engine_num: (carInfoRef.formOne.carEngineNum).toUpperCase(),
                    buy_time: carInfoRef.carEffectDate,
                    car_nature: carInfoRef.formOne.usage,
                    is_local: carInfoRef.formOne.locale,
                    nature: carInfoRef.formOne.belong,
                    transfer: carInfoRef.formOne.newly,
                    transfer_date: carInfoRef.carTransferDate,
                    mortgage: carInfoRef.formOne.mortgage,
                    beneficiary: carInfoRef.formOne.beneficiary,
                    scale: carInfoRef.formOne.benefitProportion,
                    special_agreement: carInfoRef.formOne.specially,

                    taxes_type: carInfoRef.formOne.aboutTaxesType.taxesTypeCode,
                    taxes_reason: carInfoRef.formOne.aboutTaxesReductionReason.taxesReductionReasonCode,
                    taxes_code: carInfoRef.formOne.taxesReductionReasonCodeLong,
                    taxes_organ: carInfoRef.formOne.taxesDepartment,
                    taxes_program: carInfoRef.formOne.aboutTaxesReductionPlan.taxesReductionPlanCode,
                    taxes_no: carInfoRef.formOne.taxesNo,
                    taxes_amount: carInfoRef.formOne.taxesReduction,
                    taxes_proportion: carInfoRef.formOne.taxesReductionRate / 100 || 0,
                    fuel_type: carInfoRef.formOne.aboutEnergy.energyCode,

                    /**
                     * 表单二
                     */
                    insured: carInfoRef.formTwo.recognizeeSameAsOwner,

                    // 被保人信息（非必传）

                    insured_name: carInfoRef.formTwo.recognizeeSameAsOwner === '1' ? '' : carInfoRef.formTwo.recognizee,
                    insured_num: carInfoRef.formTwo.recognizeeSameAsOwner === '1' ? '' : carInfoRef.formTwo.recognizeeIdNum,
                    insured_phone: carInfoRef.formTwo.recognizeeSameAsOwner === '1' ? '' : carInfoRef.formTwo.recognizeeTel,

                    policy_holder: carInfoRef.formTwo.applicant,

                    // 投保人信息（非必传）

                    policy_name: carInfoRef.formTwo.applicantName,
                    policy_num: carInfoRef.formTwo.applicantIdNum,
                    policy_phone: carInfoRef.formTwo.applicantTel,

                    /**
                     * 表单三
                     */

                    car_url: carInfoRef.carPicturesArr,
                    remark: carInfoRef.otherPicturesArr,
                    certificate_url: carInfoRef.formThree.evidence[0].img,
                    invoice: carInfoRef.formThree.evidence[1].img,

                    // 有车牌时必传（修改）

                    car_id: this.car_id,
                    driving_face: carInfoRef.formThree.licence[0].img,
                    driving_back: carInfoRef.formThree.licence[1].img,
                    invoice2: carInfoRef.formThree.licence[2].img
                  }
                },
                success: (res) => {
                  this.$tool.whenToast(
                    () => {

                      // 提示并禁止重复提交，不再恢复（组件即将销毁）

                      this.submitDisabled = true;
                    },
                    {
                      message: '提交成功，请继续填写保单信息',
                      className: 'public-long-toast',
                      duration: -1
                    },
                    () => {
                      this.$router.push({
                        name: 'FillInsurancePolicy',
                        params: {
                          type: this.$route.params.type,
                          car_owner_id: res.data.data.car_owner_id,
                          car_id: res.data.data.car_id
                        }
                      });
                    },2000
                  );
                }
              })
            }
          });
        }
      },

      // OCR身份证
      ocrParseIDToText() {
        this.$refs['comp-owner-info'].ocrParseToText();
      },

      // OCR驾驶证
      ocrParseLicenceToText() {
        this.$refs['comp-car-info'].ocrParseToText();
      },

      isOwnerPersonType(val) {
        this.$refs['comp-car-info'].formTwo.recognizeeIdNumLabel = +val === 1 ? '被保人身份证号' : '社会信用代码';
        this.$refs['comp-car-info'].formTwo.applicantIdNumLabel = +val === 1 ? '投保人身份证号' : '社会信用代码';
      }
    },
    created() {
      this.$http.post({
        api: this.$api.USER_ORDER_DETAIL,
        params: {
          id: this.$route.params.order_id,
          status: this.$route.params.status
        },
        success: (res) => {

          let info = res.data.data;

          this.ownerInfo = {
            ownerType: info.car_owner_type,

            name: info.coname,
            idNum: info.num,
            idEffectTime: info.end_date || '请选择-请选择-请选择',
            licence: info.plate_num,
            licenceType: info.plate_num_type,
            tel: info.phone,
            address: info.address,
            contact: info.linkman,
            contactGender: info.sex,
            idFront: info.id_card_face,
            idBack: info.id_card_back
          };

          if (this.ownerInfo.licence) {
            this.gotLicenceOrNot = true;
            this.type = 'continue'
          } else {
            this.gotEvidenceOrNot = true;
            this.type = 'new'
          }

          this.carInfo = {
            carBrand: info.model,
            place: info.provice,
            type: info.traffic,
            carNum: info.vin,
            carEngineNum: info.engine_num,
            date: info.buy_time || '请选择-请选择-请选择',
            usage: info.car_nature,
            locale: info.is_local,
            belong: info.nature,
            newly: info.transfer,
            carTransferDate: info.transfer_date,
            mortgage: info.mortgage,
            beneficiary: info.beneficiary,
            benefitProportion: info.scale,
            specially: info.special_agreement,

            taxesTypeCode: info.taxes_type,
            taxesReductionReasonCode: info.taxes_reason,
            taxesReductionReasonCodeLong: info.taxes_code,
            taxesDepartment: info.taxes_organ,
            taxesReductionPlanCode: info.taxes_program,
            taxesNo: info.taxes_no,
            taxesReduction: info.taxes_amount,
            taxesReductionRate: info.taxes_proportion,
            energyCode: info.fuel_type,

            recognizeeSameAsOwner: info.insured,
            recognizee: info.insured_name,
            recognizeeIdNum: info.insured_num,
            recognizeeTel: info.insured_phone,
            applicant: info.policy_holder,
            applicantName: info.name,
            applicantIdNum: info.policy_num,
            applicantTel: info.policy_phone,

            pictures: info.car_url,
            others: info.remark,

            evidence: [info.certificate_url, info.invoice],

            licence: [info.driving_face, info.driving_back, info.invoice2]
          };

          this.policyInfo = {
            needEvidence: info.is_get,
            byMail: info.mail,
            receiverName: info.iname,
            receiverTel: info.iphone,
            receiverAddress: info.iaddress || '',
            storageReceiverAddress: info.iaddress,

            effectTiming: info.is_immefc,
            insuranceEffectDate: info.istart_time,
            advancedInsuranceEffectTime: info.hours,

            jqEffectTiming: info.jq_is_immefc,
            jqInsuranceEffectDate: info.jq_istart_time,
            jqAdvancedInsuranceEffectTime: info.jq_hours
          };

          this.car_owner_id = info.car_owner_id;
          this.car_id = info.car_id;
          this.policy_id = info.policy_id;

          this.infoReady = true;
        }
      })
    }
  }
</script>

<style lang="scss">


  #mine-order-pending {
    padding-bottom: $public-footer-btn-box-height;

    >.public-btn-box {
      background: $white;
    }
  }
</style>
